<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/roles' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>活动管理</el-breadcrumb-item>
            <el-breadcrumb-item>活动列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>
            <el-row>
                <el-col>
                    <el-button type="primary" @click="addRoleDialogVisible = true">添加角色</el-button>
                </el-col>
            </el-row>

            <el-table
                    :data="roleList"
                    style="width: 100%"
                    border
                    stripe>
                <el-table-column
                        type="expand"
                        label="展开">
                    <template slot-scope="scope">
                        <el-row :class="['bdbottom',i1==0?'bdtop':'','vcenter']"
                                v-for="(item1,i1) in scope.row.children"
                                :key="item1.id">
                            <el-col :span="5">
                                <el-tag>{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <el-col :span="19">
                                <el-row :class="[i2==0?'':'bdtop','vcenter']" v-for="(item2,i2) in item1.children"
                                        :key="item2.id">
                                    <el-col :span="6">
                                        <el-tag type="success">{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id"
                                                closable @close="removeRightById(scope.row,item3.id)">
                                            {{item3.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>

                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column
                        type="index"
                        label="编号">
                </el-table-column>
                <el-table-column
                        prop="roleName"
                        label="角色名称">
                </el-table-column>
                <el-table-column
                        prop="roleDesc"
                        label="角色描述">
                </el-table-column>
                <el-table-column
                        label="操作">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditRoles(scope.row.id)">
                            编辑
                        </el-button>
                        <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeRole(scope.row.id)">
                            删除
                        </el-button>
                        <el-button type="warning" size="mini" icon="el-icon-setting" @click="setRight(scope.row)">分配权限
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>


        <el-dialog
                title="添加角色"
                :visible.sync="addRoleDialogVisible"
                width="50%"
                @close="addRoleFormClose">
            <el-form ref="addRoleFormRef" :model="addRoleForm" :rules="addRoleFormRules">
                <el-form-item label="角色名" prop="roleName">
                    <el-input v-model="addRoleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addRoleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
    <el-button @click="addRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addRole">确 定</el-button>
  </span>
        </el-dialog>

        <el-dialog
                title="添加角色"
                :visible.sync="EditRolesDialogVisible"
                width="50%"
                @close="editRoleFormClose">
            <el-form ref="editRoleFormRef" :model="editRoleForm" :rules="editRoleFormRules">
                <el-form-item label="角色名" prop="roleName">
                    <el-input v-model="editRoleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editRoleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
    <el-button @click="EditRolesDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="EditRoles">确 定</el-button>
  </span>
        </el-dialog>

        <el-dialog
                title="分配权限"
                :visible.sync="setRightDialogVisible"
                width="50%"
                @close="setRightDialogClose">
            <el-tree :data="rightList" :props="treeProps" show-checkbox node-key="id" default-expand-all
                     :default-checked-keys="defKey" ref="treeRef"></el-tree>

            <span slot="footer" class="dialog-footer">
    <el-button @click="setRightDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "Roles",
        data() {
            return {
                roleList: [],
                addRoleDialogVisible: false,
                addRoleForm: {
                    roleName: '',
                    roleDesc: ''
                },
                addRoleFormRules: {
                    roleName: [
                        {required: true, message: '请输入角色名称', trigger: 'blur'},
                        {min: 1, max: 6, message: '长度在 1 到 6 个字符', trigger: 'blur'}
                    ],
                    roleDesc: [
                        {required: true, message: '请输入角色描述', trigger: 'blur'},
                        {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
                    ]
                },
                EditRolesDialogVisible: false,
                editRoleFormRules: {
                    roleName: [
                        {required: true, message: '请输入角色名称', trigger: 'blur'},
                        {min: 1, max: 6, message: '长度在 1 到 6 个字符', trigger: 'blur'}
                    ],
                    roleDesc: [
                        {required: true, message: '请输入角色描述', trigger: 'blur'},
                        {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
                    ]
                },
                editRoleForm: {},
                setRightDialogVisible: false,
                rightList: [],
                treeProps: {
                    label: 'authName',
                    children: 'children'
                },
                defKey: [],
                roleId:'',
            }
        },
        created() {
            this.getRolesList();
        },
        methods: {
            async getRolesList() {
                const {data: res} = await this.$http.get('roles');
                if (res.meta.status != 200) {
                    return this.$message.error('请求列表错误');
                }
                this.roleList = res.data;
            },
            addRole() {

                this.$refs.addRoleFormRef.validate(async valid => {
                    if (!valid) {
                        return;
                    }
                    const {data: res} = await this.$http.post('roles', this.addRoleForm);
                    if (res.meta.status != 201) {
                        return this.$message.error('添加失败');
                    }
                    this.$message.success('添加成功');
                    this.addRoleDialogVisible = false;
                    this.getRolesList();
                })
            },
            addRoleFormClose() {
                this.$refs.addRoleFormRef.resetFields();
            },

            removeRole(id) {
                this.$confirm('此操作将永久删除该角色, 是否继续?', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    const {data: res} = await this.$http.delete('roles/' + id);
                    console.log(res);
                    if (res.meta.status != 200) {
                        return this.$message.error('删除失败');
                    }
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getRolesList();
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            async showEditRoles(id) {

                this.EditRolesDialogVisible = true;
                const {data: res} = await this.$http.get('roles/' + id);
                if (res.meta.status != 200) {
                    return this.$message.error('获取用户失败');
                }
                this.editRoleForm = res.data;


            },

            editRoleFormClose() {
                this.$refs.editRoleFormRef.resetFields();
            },

            EditRoles() {
                this.$refs.editRoleFormRef.validate(async valid => {
                    if (!valid) {
                        return;
                    }
                    const {data: res} = await this.$http.put('roles/' + this.editRoleForm.roleId, {
                            roleName: this.editRoleForm.roleName,
                            roleDesc: this.editRoleForm.roleDesc
                        }
                    );
                    console.log(res);
                    this.$message.success('修改成功');
                    this.EditRolesDialogVisible = false;
                    this.getRolesList();
                })
            },
            removeRightById(role, id) {
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    const {data: res} = await this.$http.delete(`roles/${role.id}/rights/${id}`);
                    if (res.meta.status != 200) {
                        this.$message.error("操作失败");
                    }
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    role.children = res.data;
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            async setRight(role) {
                this.roleId=role.id;
                const {data: res} = await this.$http.get('rights/tree');
                if (res.meta.status != 200) {
                    this.$message.error("获取权限失败");
                }
                this.rightList = res.data;

                this.getLeafKeys(role, this.defKey)
                this.setRightDialogVisible = true;
            },

            getLeafKeys(node, arr) {
                if (!node.children) {
                    return arr.push(node.id);
                }
                node.children.forEach(item => {
                    this.getLeafKeys(item, arr)
                })
            },

            setRightDialogClose() {
                this.defKey = [];
            },

            async allotRights() {
                const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()];
                const keyStr = keys.join(',');
                const {data:res}=await this.$http.post(`roles/${this.roleId}/rights`,{rids:keyStr});
                if (res.meta.status!=200){
                    this.$message.error("分配权限失败");
                }
                this.$message.success("分配权限成功");
                this.setRightDialogVisible = false;
                this.getRolesList();
            },
        }
    }
</script>

<style scoped lang="less">
    .el-tag {
        margin: 7px;
    }

    .bdbottom {
        border-bottom: 1px solid #eee;
    }

    .bdtop {
        border-top: 1px solid #eee;
    }

    .vcenter {
        display: flex;
        align-items: center;
    }
</style>